package com.doublefish.doublefishrobot.utils.db;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.doublefish.doublefishrobot.ui.home.bean.ModeSettingBean;
import com.doublefish.doublefishrobot.ui.setting.model.AppInfoBean;
import com.doublefish.doublefishrobot.ui.home.bean.DeviceBean;
import com.doublefish.doublefishrobot.ui.home.bean.FirmwareInfoBean;
import com.doublefish.doublefishrobot.ui.video.bean.VideoInfoBean;
import com.doublefish.doublefishrobot.utils.db.database.SQLiteDatabaseManager;
import com.doublefish.doublefishrobot.utils.db.database.SQLiteSentenceCreatHelper;
import com.doublefish.doublefishrobot.utils.db.database.bean.SQLiteResult;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者:dugaofeng on 2024/10/16 14:35
 */
public class DataBaseApi {

    //创建数据库
    public static void createDB(Context context) {
        if (context == null) {
            return;
        }
        if (SQLiteDatabaseManager.getInstance().isDidCreatDataBase()) {
            return;
        }
        //初始化数据库和表的信息
        SQLiteSentenceCreatHelper helper = new SQLiteSentenceCreatHelper();
        //创建数据库
        SQLiteDatabaseManager.getInstance().creatDataBaseTables(context, helper.dbPath(context), helper.dbPwd(), helper.getDbVersion(), helper.getSqlInfoModelList());
    }

    //region 设备列表

    //查询绑定设备列表
    public static void queryBindDeviceList(OnQueryBindDeviceListListner listner) {
        if (listner == null) {
            return;
        }
        String sql = "select * from " +
                SQLiteSentenceCreatHelper.TABLE_BIND_DEVICE +
                " order by updateTime DESC";
        SQLiteResult result = SQLiteDatabaseManager.getInstance().queryData(sql);

        if (result.isSuccess()) {
            if (result.getList() == null || result.getList().size() == 0) {
                listner.onCallback(true, null);
            } else {
                List<DeviceBean> list = JSON.parseArray(JSON.toJSONString(result.getList()), DeviceBean.class);
                listner.onCallback(true, list);
            }
        } else {
            listner.onCallback(false, null);
        }
    }

    //保存绑定设备信息
    public static void saveDeviceInfo(DeviceBean deviceBean, OnDatabaseCommonListner listner) {
        SQLiteResult result = null;
        if (deviceBean.getTid() > 0) {
            //更新数据
            Map<String, Object> data = deviceBean.toDataBaseMap();

            Map<String, Object> where = new HashMap<String, Object>();
            where.put("t_id", deviceBean.getTid());

            result = SQLiteDatabaseManager.getInstance().updataData(SQLiteSentenceCreatHelper.TABLE_BIND_DEVICE, data, where);
        } else {
            //插入数据
            Map<String, Object> data = deviceBean.toDataBaseMap();
            result = SQLiteDatabaseManager.getInstance().insertData(SQLiteSentenceCreatHelper.TABLE_BIND_DEVICE, data);
        }
        if (listner != null) {
            listner.onCallback(result != null && result.isSuccess());
        }
    }

    //删除绑定设备信息
    public static void deleteDeviceInfo(DeviceBean deviceBean, OnDatabaseCommonListner listner) {
        SQLiteResult result = null;
        if (deviceBean.getTid() == 0) {
            listner.onCallback(false);
            return;
        }
        //删除数据
        Map<String, Object> where = new HashMap<String, Object>();
        where.put("t_id", deviceBean.getTid());

        result = SQLiteDatabaseManager.getInstance().deleteData(SQLiteSentenceCreatHelper.TABLE_BIND_DEVICE, where);
        if (listner != null) {
            listner.onCallback(result != null && result.isSuccess());
        }
    }

    //更新设备列表的updateTime
    public static void updateLastDevice(DeviceBean deviceBean, OnDatabaseCommonListner listner) {
        if (deviceBean.getTid() == 0) {
            listner.onCallback(false);
            return;
        }

        String sql = "UPDATE " + SQLiteSentenceCreatHelper.TABLE_BIND_DEVICE
                + " SET updateTime=(datetime('now', 'localtime')) where t_id="
                + deviceBean.getTid() + ";";

        SQLiteResult result = SQLiteDatabaseManager.getInstance().updateData(sql);
        if (listner != null) {
            listner.onCallback(result != null && result.isSuccess());
        }
    }

    //endregion


    //region app信息
    //查询app信息
    public static void queryAppInfo(int client, OnQueryAppInfoListner listner) {
        if (listner == null) {
            return;
        }
        String sql = "select * from " +
                SQLiteSentenceCreatHelper.TABLE_APP_INFO +
                " where client=" + client;
        SQLiteResult result = SQLiteDatabaseManager.getInstance().queryData(sql);

        if (result.isSuccess()) {
            if (result.getList() == null || result.getList().size() == 0) {
                listner.onCallback(true, null);
            } else {
                AppInfoBean bean = JSONObject.parseObject(JSON.toJSONString(result.getData()), AppInfoBean.class);
                listner.onCallback(true, bean);
            }
        } else {
            listner.onCallback(false, null);
        }
    }

    //保存app信息
    public static void saveAppInfo(AppInfoBean bean, OnDatabaseCommonListner listner) {

        SQLiteResult result = null;
        if (bean.getTid() > 0) {
            //更新数据
            Map<String, Object> data = new HashMap<>();
            data.put("ver", bean.getVer());
            data.put("path", bean.getPath());

            Map<String, Object> where = new HashMap<String, Object>();
            where.put("t_id", bean.getTid());

            result = SQLiteDatabaseManager.getInstance().updataData(SQLiteSentenceCreatHelper.TABLE_APP_INFO, data, where);
        } else {
            //插入数据
            Map<String, Object> data = new HashMap<>();
            data.put("client", bean.getClient());
            data.put("client_name", bean.getClient_name());
            data.put("ver", bean.getVer());
            data.put("path", bean.getPath());

            result = SQLiteDatabaseManager.getInstance().insertData(SQLiteSentenceCreatHelper.TABLE_APP_INFO, data);
        }
        if (listner != null) {
            listner.onCallback(result != null && result.isSuccess());
        }
    }

    //endregion

    //region 固件信息
    //查询固件信息
    public static void queryFirmwareInfo(int model,OnFirmwareInfoListner listner) {
        if (listner == null) {
            return;
        }
        String sql = "select * from " +
                SQLiteSentenceCreatHelper.TABLE_FIRMWARE_INFO+
                " where model=" + model;
        SQLiteResult result = SQLiteDatabaseManager.getInstance().queryData(sql);

        if (result.isSuccess()) {
            if (result.getList() == null || result.getList().size() == 0) {
                listner.onCallback(true, null);
            } else {
                FirmwareInfoBean bean = JSONObject.parseObject(JSON.toJSONString(result.getData()), FirmwareInfoBean.class);
                listner.onCallback(true, bean);
            }
        } else {
            listner.onCallback(false, null);
        }
    }

    //保存固件信息
    public static void saveFirmwareInfo(FirmwareInfoBean bean, OnDatabaseCommonListner listner) {
        SQLiteResult result = null;
        if (bean.getTid() > 0) {
            //更新数据
            Map<String, Object> data = new HashMap<>();
            data.put("ver", bean.getVer());
            data.put("path", bean.getPath());
            data.put("hash", bean.getHash());
            data.put("size", bean.getSize());

            Map<String, Object> where = new HashMap<String, Object>();
            where.put("t_id", bean.getTid());

            result = SQLiteDatabaseManager.getInstance().updataData(SQLiteSentenceCreatHelper.TABLE_FIRMWARE_INFO, data, where);
        } else {
            //插入数据
            Map<String, Object> data = new HashMap<>();
            data.put("model", bean.getModel());
            data.put("ver", bean.getVer());
            data.put("path", bean.getPath());
            data.put("hash", bean.getHash());
            data.put("size", bean.getSize());

            result = SQLiteDatabaseManager.getInstance().insertData(SQLiteSentenceCreatHelper.TABLE_FIRMWARE_INFO, data);
        }
        if (listner != null) {
            listner.onCallback(result != null && result.isSuccess());
        }
    }

    //endregion


    //region 自定义模式列表

    /// 查询自定义模式列表
    /// - Parameters:
    ///   - model: 型号 int  1.超8  2.超6  3.超6  4.超3
    ///   - keyword: 搜索的关键字
    ///   - listner: 回调
    public static void queryCustomModelList(int model, String keyword, OnQueryCustomModelListListner listner) {
        if (listner == null) {
            return;
        }
        String sql = "select * from " +
                SQLiteSentenceCreatHelper.TABLE_CUSTOM_MODEL +
                " where model = " + model;
        if (keyword != null && keyword.trim().length() > 0) {
            sql += " and name like '%" + keyword + "%'";
        }
        sql += " order by updateTime DESC";
        SQLiteResult result = SQLiteDatabaseManager.getInstance().queryData(sql);
        if (result.isSuccess()) {
            if (result.getList() == null || result.getList().size() == 0) {
                listner.onCallback(true, null);
            } else {
                List<ModeSettingBean> list = JSON.parseArray(JSON.toJSONString(result.getList()), ModeSettingBean.class);
                listner.onCallback(true, list);
            }
        } else {
            listner.onCallback(false, null);
        }
    }

    //保存自定义模式
    //model: 型号 int  1.超8  2.超6  3.超5  4.超3
    public static void saveCustomModelInfo(int model,ModeSettingBean settingBean, OnDatabaseCommonListner listner) {
        SQLiteResult result = null;
        if (settingBean.getTid() > 0) {
            //更新数据
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("name", settingBean.getName());
            data.put("script", settingBean.getScript());

            Map<String, Object> where = new HashMap<String, Object>();
            where.put("t_id", settingBean.getTid());

            result = SQLiteDatabaseManager.getInstance().updataData(SQLiteSentenceCreatHelper.TABLE_CUSTOM_MODEL, data, where);
        } else {
            //插入数据
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("model", model);
            data.put("name", settingBean.getName());
            data.put("script", settingBean.getScript());

            result = SQLiteDatabaseManager.getInstance().insertData(SQLiteSentenceCreatHelper.TABLE_CUSTOM_MODEL, data);
        }
        if (listner != null) {
            listner.onCallback(result != null && result.isSuccess());
        }
    }

    //删除自定义模式
    public static void deleteCustomModel(ModeSettingBean settingBean, OnDatabaseCommonListner listner) {
        SQLiteResult result = null;
        if (settingBean.getTid() == 0) {
            listner.onCallback(false);
            return;
        }
        //删除数据
        Map<String, Object> where = new HashMap<String, Object>();
        where.put("t_id", settingBean.getTid());

        result = SQLiteDatabaseManager.getInstance().deleteData(SQLiteSentenceCreatHelper.TABLE_CUSTOM_MODEL, where);
        if (listner != null) {
            listner.onCallback(result != null && result.isSuccess());
        }
    }
    //endregion


    //region 视频列表
    //查询视频信息列表
    public static void queryVideoList(OnQueryVideoListListner listner) {
        if (listner == null) {
            return;
        }
        String sql = "select * from " +
                SQLiteSentenceCreatHelper.TABLE_VIDEO_LIST +
                " order by t_id ASC";

        SQLiteResult result = SQLiteDatabaseManager.getInstance().queryData(sql);
        if (result.isSuccess()) {
            if (result.getList() == null || result.getList().size() == 0) {
                listner.onCallback(true, null);
            } else {
                List<VideoInfoBean> list = JSON.parseArray(JSON.toJSONString(result.getList()), VideoInfoBean.class);
                listner.onCallback(true, list);
            }
        } else {
            listner.onCallback(false, null);
        }
    }

    //保存视频信息
    public static void saveVideo(VideoInfoBean bean, OnDatabaseCommonListner listner) {
        SQLiteResult result = null;
        if (bean.getTid() > 0) {
            //更新数据
            Map<String, Object> data = bean.toDataBaseMap();

            Map<String, Object> where = new HashMap<String, Object>();
            where.put("t_id", bean.getTid());

            result = SQLiteDatabaseManager.getInstance().updataData(SQLiteSentenceCreatHelper.TABLE_VIDEO_LIST, data, where);
        } else {
            //插入数据
            Map<String, Object> data = bean.toDataBaseMap();
            result = SQLiteDatabaseManager.getInstance().insertData(SQLiteSentenceCreatHelper.TABLE_VIDEO_LIST, data);
        }
        if (listner != null) {
            listner.onCallback(result != null && result.isSuccess());
        }
    }
    //保存视频信息 (批量操作)
    public static void saveVideos(List<VideoInfoBean> list, OnDatabaseCommonListner listner) {
        //开始事务
        SQLiteDatabaseManager.getInstance().beginTransaction();

        SQLiteResult result = null;
        for (VideoInfoBean bean: list) {
            if (bean.getTid() > 0) {
                //更新数据
                Map<String, Object> data = bean.toDataBaseMap();

                Map<String, Object> where = new HashMap<String, Object>();
                where.put("t_id", bean.getTid());

                result = SQLiteDatabaseManager.getInstance().updataData(SQLiteSentenceCreatHelper.TABLE_VIDEO_LIST, data, where);
            } else {
                //插入数据
                Map<String, Object> data = bean.toDataBaseMap();
                result = SQLiteDatabaseManager.getInstance().insertData(SQLiteSentenceCreatHelper.TABLE_VIDEO_LIST, data);
            }

            if (result == null || !result.isSuccess()) {
                //回滚事务
                SQLiteDatabaseManager.getInstance().endTransaction();
                if (listner != null) {
                    listner.onCallback(false);
                }
                return;
            }
        }
        //完成事务
        SQLiteDatabaseManager.getInstance().setTransactionSuccessful();
        SQLiteDatabaseManager.getInstance().endTransaction();
        if (listner != null) {
            listner.onCallback(true);
        }
    }

    //endregion


    public interface OnDatabaseCommonListner {
        void onCallback(boolean suc);
    }

    public interface OnQueryBindDeviceListListner {
        void onCallback(boolean suc, List<DeviceBean> list);
    }

    public interface OnQueryAppInfoListner {
        void onCallback(boolean suc, AppInfoBean bean);
    }

    public interface OnFirmwareInfoListner {
        void onCallback(boolean suc, FirmwareInfoBean bean);
    }

    public interface OnQueryCustomModelListListner {
        void onCallback(boolean suc, List<ModeSettingBean> list);
    }

    public interface OnQueryVideoListListner {
        void onCallback(boolean suc, List<VideoInfoBean> list);
    }
}
